<template>
  <div>
    <a-modal
      title="分组管理"
      :visible="visible"
      @ok="handleCancel"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      width="1070px">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col
                :md="6"
                :sm="24">
                <a-form-item label="资源名称">
                  <a-input
                    v-model="queryParam.dto.fileName"
                    placeholder="" />
                </a-form-item>
              </a-col>
              <a-col
                :md="6"
                :sm="24">
                <span
                  class="table-page-search-submitButtons"
                  :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button
                    type="primary"
                    @click="search(1)">查询</a-button>
                  <a-button
                    style="margin-left: 8px"
                    @click="search(2)">重置</a-button>
                </span>
              </a-col>
            </a-row>

          </a-form>
        </div>

        <div v-if="groups.length>0">
          <a-button
            @click="setQueryParam(group.id,index)"
            :key="index"
            v-for="(group,index) in groups"
            :class="activeClass ==index?'selectBton':''"
            style="margin-left: 10px;margin-bottom: 5px ;"
            type="round"
            icon="search">
            {{ group.name }}({{ group.fileCount }})</a-button>
        </div>

        <a-divider />

        <a-row >
          <a-col :md="6" :sm="24" v-for="(data,index) in datas" :key="index" @click="insertIt(data)">
            <a-card hoverable >
              <img
                v-if="!isVideo(data.fileType)"
                alt="example"
                :src="coverFileCover(data.fileFullPath,data.fileType)"
                style="width:54%;height:230px;object-fit: cover;overflow-y: hidden;margin-left: 22%;"
                slot="cover"
              />
              <video style="width:100%;height:225px;object-fit: fill;overflow-y: hidden" loop="loop" autoplay="autoplay" :src="data.fileFullPath" v-if="isVideo(data.fileType)"/>
              <template class="ant-card-actions" slot="actions">

                <a-popconfirm
                  title="确定要删除该文件吗？"
                  @confirm="deleteFile(data.fileUid)"
                  okText="确认"
                  cancelText="取消">
                  <span v-action:resource:del><a-icon type="delete" /></span>
                </a-popconfirm>

                <a-tooltip>
                  <template slot="title">
                    复制标题
                  </template>
                  <a-icon type="copy" @click="copyIt(data.fileName)"/>
                </a-tooltip>

                <a-tooltip>
                  <template slot="title">
                    复制链接
                  </template>
                  <a-icon type="copy" @click="copyIt(data.fileFullPath)"/>
                </a-tooltip>

                <a-tooltip>
                  <template slot="title">
                    下载文件
                  </template>
                  <a-icon type="arrow-down" @click="downIt(data.id)"/>
                </a-tooltip>
              </template>
              <a-card-meta :title="data.fileName" :description="'大小:'+conver(data.fileSize)+' 日期:'+converDate(data.gmtCreate)">
              </a-card-meta>
            </a-card>
            <a-divider type="horizontal" :dashed="true"/>
          </a-col>
        </a-row>

        <a-pagination :current="queryParam.pageNo" :pageSize="queryParam.pageSize" :total="total" @change="loadChange" v-if="datas.length>0"/>

      </a-card>

    </a-modal>
  </div>
</template>
<script>

  import moment from 'moment'
  import { pageMedia, deleteFile, listGroup, updateFileGid, downFile } from '@/api/site/upFile'
  import { STable } from '@/components'

  export default {
    components: {
      STable
    },
    data () {
      return {
        visible: false,
        confirmLoading: false,
        groups: [],
        showEdit: false,
        mdl: {},
        advanced: false,
        queryParam: {
          dto: {
          },
          pageNo: 1,
          pageSize: 12
        },
        datas: [],
        total: 0,
        fileGroupId: null,
        activeClass: 0,
        video: []
      }
    },
    methods: {
      openMedia () {
        this.visible = true
        this.loadData()
      },
      handleOk (e) {
          this.loadData()
      },
     search (type) {
        this.queryParam.pageNo = 1
        if (type === 2) {
           this.queryParam.dto.fileName = null
           this.queryParam.dto.fileGroupId = '-1'
           this.fileGroupId = null
           this.activeClass = 0
        }
        this.loadData()
     },
     loadChange (page, pageSize) {
        this.queryParam.pageNo = page
        this.loadData()
     },
     insertIt (data) {
       if (data) {
        const images = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'svg', 'tiff', 'jfif']
        var fileExtension = data.fileName.substring(data.fileName.lastIndexOf('.') + 1)
        if (images.indexOf(fileExtension) >= 0) {
            const content = "<img src='" + data.fileFullPath + "'/>"
            this.$emit('insertOk', 'mceReplaceContent', content)
        } else {
            const content = "<a target='_blank' href='" + data.fileFullPath + "'>" + data.fileName + '</a>'
            this.$emit('insertOk', 'insertHTML', content)
        }
       }
       console.log(data)
     },
     copyIt (content) {
           const input = document.createElement('input')
           document.body.appendChild(input)
           input.setAttribute('value', content)
           input.select()
           if (document.execCommand('copy')) {
               document.execCommand('copy')
               this.$message.info('复制成功!')
           }
           document.body.removeChild(input)
     },
     setQueryParam (fileGroupId, index) {
       this.fileGroupId = fileGroupId
       this.activeClass = index
       this.queryParam.dto.fileGroupId = fileGroupId
       this.loadData()
     },
     loadData () {
       pageMedia(this.queryParam).then(response => {
         if (response.code === 0) {
           this.total = response.res.total
           this.datas = response.res.rows
         }
       })

       listGroup({}).then(response => {
         this.groups = response.res
          console.log(response)
       })
     },
     downIt (id) {
       downFile({ id: id }).then(response => {
         const blob = new Blob([response.data])
         const linkNode = document.createElement('a')
         linkNode.download = response.headers.filename // a标签的download属性规定下载文件的名称
         linkNode.style.display = 'none'
         linkNode.href = URL.createObjectURL(blob) // 生成一个Blob URL
         document.body.appendChild(linkNode)
         linkNode.click() // 模拟在按钮上的一次鼠标单击
         URL.revokeObjectURL(linkNode.href) // 释放URL 对象
         document.body.removeChild(linkNode)
       })
     },
     deleteFile (fileUid) {
       deleteFile({ fileUid: fileUid }).then(response => {
         if (response.code === 0) {
            this.$message.info('删除成功!')
            this.loadData()
         } else {
           this.$message.error(response.msg)
         }
       })
     },
     coverFileCover (fileFullPath, fileType) {
        let cover = '/default_file.png'
        if (fileFullPath && fileType) {
           const images = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'svg', 'tiff', 'jfif']
           if (images.indexOf(fileType) >= 0) {
             cover = fileFullPath
           }
        }
        return cover
     },
     isVideo (fileType) {
       if (fileType) {
         const videos = ['avi', 'rmvb', 'flv', 'mkv', 'mp4', '3gp', 'asf', 'f4v', 'qsv', 'hddvd', 'ogv']
         return videos.indexOf(fileType) >= 0
       } else {
         return false
       }
     },
     managerGroup () {
          this.$refs.managerHandle.show()
     },
     converDate (date) {
       return moment(date).format('YYYY-MM-DD')
     },
     conver (limit) {
             if (!limit) {
               return '未知'
             }
             var size = ''
             if (limit < 0.1 * 1024) { // 如果小于0.1KB转化成B
                 size = limit.toFixed(2) + 'B'
             } else if (limit < 0.1 * 1024 * 1024) { // 如果小于0.1MB转化成KB
                 size = (limit / 1024).toFixed(2) + 'KB'
             } else if (limit < 0.1 * 1024 * 1024 * 1024) { // 如果小于0.1GB转化成MB
                 size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
             } else { // 其他转化成GB
                 size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
             }

             var sizestr = size + ''
             var len = sizestr.indexOf('\\.')
             var dec = sizestr.substr(len + 1, 2)
             if (dec === '00') { // 当小数点后为00时 去掉小数部分
                 return sizestr.substring(0, len) + sizestr.substr(len + 3, 2)
             }
             return sizestr
     },
      handleCancel (e) {
        this.activeClass = -1
        this.visible = false
      },
      onChange (e) {

      }
    }
  }
</script>
<style>
  .selectBtn{
     display:block!important
  }
  .selectNoBtn{
     display:none!important
  }
</style>
